#include "HeroPool.h"
#include "Hero.h"
#include "Sheet.h"

HeroPool* HeroPool::instance()
{
	static HeroPool pool;
	return &pool;
}

HeroPool::HeroPool()
{
	AddHero_Sheet("..\\res\\sheet.txt");
}
void HeroPool::AddHero(int id, Hero* hero)
{
	m_pool.insert(std::make_pair<int,Hero*>(id, hero));
}

void HeroPool::ForEachHero( HeroFunc func )
{
	HMIter itCur = m_pool.begin();
	HMIter itEnd = m_pool.end();
	while(itCur != itEnd)
	{
		int id = itCur->first;
		Hero* hero = itCur->second;
		func(id, hero);
		itCur++;
	}
}

void HeroPool::AddHero_Sheet( const char* filename )
{
	Sheet* heros = LoadSheet(filename);
	if(!heros)
		return;

	int cID		= heros->GetColumn("id");
	int cName	= heros->GetColumn("name");
	int cAttrib	= heros->GetColumn("attribute");
	int cAttack	= heros->GetColumn("attack");
	int cSkill	= heros->GetColumn("skill");
	

	EntryIter* itCur = heros->GetFirst();
	EntryIter* itEnd = heros->GetLast();
	while(*itCur != *itEnd)
	{
		Entry* entry = itCur->GetEntry();

		string name	= entry->GetCell(cName)->toStr();
		int id		= entry->GetCell(cID)->toInt();
		int attack	= entry->GetCell(cAttack)->toInt();
		int attrib	= entry->GetCell(cAttrib)->toInt();
		int skillID	= entry->GetCell(cSkill)->toInt();

		Hero* hero = new Hero(name, attack, attrib, skillID);
		AddHero(id, hero);

		itCur->Next();
	}
	delete heros;
}

Hero* HeroPool::GetRanddomHero()
{
	int id = rand() % m_pool.size();
	HMIter itCur = m_pool.begin();
	for(int i = 0; i != id; i++)
	{
		itCur++;
	}
	return itCur->second;

}

Hero* HeroPool::GetHero(int id)
{
	HMIter itFind = m_pool.find(id);
	if(itFind != m_pool.end())
	{
		return itFind->second;
	}
	return GetRanddomHero();
}




